package com.javaweb.resolver;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.javaweb.annotation.token.TokenDataAnnotation;
import com.javaweb.base.BaseInject;
import com.javaweb.base.po.Interfaces;
import com.javaweb.constant.SystemConstant;
import com.javaweb.constant.SystemConstant.HeadConstant;
import com.javaweb.exception.TokenExpiredException;
import com.javaweb.web.eo.TokenData;

/**
 * TokenData注解处理
 * @author tank2140896
 */
public class TokenDataResolver implements HandlerMethodArgumentResolver {
	
	/**
	 * 支持的参数表现形式
	 * <p>
	 * 作用于方法参数类型为TokenData且标记有注解TokenDataAnnotation
	 * @param parameter MethodParameter
	 * @return boolean 是否符合支持的参数表现形式（true：是；false：否）
	 */
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(TokenData.class) && parameter.hasParameterAnnotation(TokenDataAnnotation.class);
    }
    
	/**
	 * 获取TokenData
	 * @param parameter MethodParameter
	 * @param container ModelAndViewContainer
	 * @param request NativeWebRequest（这里不建议将NativeWebRequest转为HttpServeltRequest）
	 * @param factory WebDataBinderFactory
	 * @return Object TokenData
	 */
    public Object resolveArgument(MethodParameter parameter,ModelAndViewContainer container,NativeWebRequest request,WebDataBinderFactory factory) throws Exception {
		TokenData tokenData = BaseInject.getTokenData(BaseInject.getToken(request));
		if(tokenData==null){
			throw new TokenExpiredException();
		}
		Interfaces interfaces = (Interfaces)request.getAttribute(SystemConstant.REQUEST_URL_CHAIN_ATTRIBUTE_NAME,NativeWebRequest.SCOPE_REQUEST);
		tokenData.setBestMatchingPattern(interfaces.getUrl());
		tokenData.setAlias(request.getHeader(HeadConstant.HEAD_ALIAS));
		return tokenData;
    }
    
}
